using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IGlobalist.Cms.Controls
{
    public class TinyMCE : WebControl, IPostBackDataHandler
    {
        private string _javascriptLocation = "Editors/tinymce";
        private string _coreFile = "/tiny_mce.js";
        private int _rows = 13;
        private int _cols = 60;
        public NameValueCollection config;
        private string temp;

        public string CoreFile
        {
            get { return _coreFile; }
        }


        public TinyMCE()
        {
            config = new NameValueCollection();
            config.Add("mode", "exact");
            config.Add("theme", "simple");
            //content_css : "/mycontent.css"
            temp = string.Empty;
            //this._config.SetStringParam(TinyMCEConfig.StringParameter.mode, "exact");
            //this._config.SetStringParam(TinyMCEConfig.StringParameter.theme, "advanced");
            //this._config.SetStringParam(TinyMCEConfig.StringParameter.plugins, "advlink,noneditable,advimage,flash");
            //this._config.SetStringParam(TinyMCEConfig.StringParameter.theme_advanced_buttons3_add, "flash");
        }

        // <summary>
        /// The text of the editor
        /// </summary>
        public string Text
        {
            get { return (string) ViewState["text"]; }
            set { ViewState["text"] = value; }
        }


        // <summary>
        /// The number of rows in the textarea that gets converted to the editor.
        /// This affects the size of the editor. Default is 10
        /// </summary>
        public int Rows
        {
            get { return _rows; }
            set { _rows = value; }
        }

        // <summary>
        /// The number of columns in the textarea that gets converted to the editor.
        /// This affects the size of the editor. Default is 40.
        /// </summary>
        public int Cols
        {
            get { return _cols; }
            set { _cols = value; }
        }

        // <summary>
        /// Path to the TinyMCE javascript, default is "jscripts/tiny_mce/tiny_mce.js"
        /// </summary>
        public string JavascriptLocation
        {
            get { return _javascriptLocation; }
            set { _javascriptLocation = value; }
        }


        private string _Mode = "exact";
        public string Mode
        {
            get { return _Mode; }
            set { _Mode = value; }
        }

        

        private string _Theme = "advanced";
        public string Theme
        {
            get { return _Theme; }
            set { _Theme = value; }
        }

        private string _Plugins = "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,flash,searchreplace,print,contextmenu";
        public string Plugins
        {
            get { return _Plugins; }
            set { _Plugins = value; }
        }

        private string _DateFormat = "%Y-%m-%d";
        public string DateFormat
        {
            get { return _DateFormat; }
            set { _DateFormat = value; }
        }

        private string _TimeFormat = "%H:%M:%S";
        public string TimeFormat
        {
            get { return _TimeFormat; }
            set { _TimeFormat = value; }
        }

        private string _GroupOne = "%H:%M:%S";
        public string GroupOne
        {
            get { return _GroupOne; }
            set { _GroupOne = value; }
        }

        private string _GroupOneAddBefore = "save,separator";
        public string GroupOneAddBefore
        {
            get { return _GroupOneAddBefore; }
            set { _GroupOneAddBefore = value; }
        }

        private string _GroupTwo = "separator,insertdate,inserttime,preview,zoom,separator,forecolor,backcolor";
        public string GroupTwo
        {
            get { return _GroupTwo; }
            set { _GroupTwo = value; }
        }

        private string _GroupTwoAddBefore = "cut,copy,paste,separator,search,replace,separator";
        public string GroupTwoAddBefore
        {
            get { return _GroupTwoAddBefore; }
            set { _GroupTwoAddBefore = value; }
        }

        private string _GroupThree = "emotions,iespell,flash,advhr,separator,print";
        public string GroupThree
        {
            get { return _GroupThree; }
            set { _GroupThree = value; }
        }

        private string _GroupThreeAddBefore = "tablecontrols,separator";
        public string GroupThreeAddBefore
        {
            get { return _GroupThreeAddBefore; }
            set { _GroupThreeAddBefore = value; }
        }

      

        private string _ToolbarAlign = "left";
        public string ToolbarAlign
        {
            get { return _ToolbarAlign; }
            set { _ToolbarAlign = value; }
        }

        private string _ToolbarLocation = "top";
        public string ToolbarLocation
        {
            get { return _ToolbarLocation; }
            set { _ToolbarLocation = value; }
        }

        private string _PathLocation = "bottom";
        public string PathLocation
        {
            get { return _PathLocation; }
            set { _PathLocation = value; }
        }

        private string _ExtendedValidElements = "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]";
        public string ExtendedValidElements
        {
            get { return _ExtendedValidElements; }
            set { _ExtendedValidElements = value; }
        }

        private string _ExternalLinkListUrl = "../Editors/GetLinkList.aspx";
        public string ExternalLinkListUrl
        {
            get { return _ExternalLinkListUrl; }
            set { _ExternalLinkListUrl = value; }
        }

        private string _ExternalImageListUrl = "../Editors/GetLinkImageList.aspx";
        public string ExternalImageListUrl
        {
            get { return _ExternalImageListUrl; }
            set { _ExternalImageListUrl = value; }
        }
         
		        
        
        /// <summary>
        /// Draws the editor
        /// </summary>
        /// <param name="outWriter">The writer to draw the editor to</param>
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("<!-- tinyMCE -->\n");
//            writer.WriteLine("<script language=\"javascript\" type=\"text/javascript\" src=\"" + JavascriptLocation + "\"/>\n");
            writer.WriteLine("<script language=\"javascript\" type=\"text/javascript\">");
            writer.WriteLine("tinyMCE.init({");
            string s = @"mode : '{0}',
	            theme : '{1}',
	            plugins : '{2}',
	            theme_advanced_buttons1_add_before : '{3}',
	            theme_advanced_buttons1_add : '{4}',
	            theme_advanced_buttons2_add : '{5}',
	            theme_advanced_buttons2_add_before: '{6}',
	            theme_advanced_buttons3_add_before : '{7}',
	            theme_advanced_buttons3_add : '{8}',
	            theme_advanced_toolbar_location : '{9}',
	            theme_advanced_toolbar_align : '{10}',
	            theme_advanced_path_location : '{11}',
	            plugin_insertdate_dateFormat : '{12}',
	            plugin_insertdate_timeFormat : '{13}',
	            extended_valid_elements : '{14}',
                external_link_list_url : '{15}',
		        external_image_list_url : '{16}',";

            s = String.Format(s, this.Mode, this.Theme,
                        this.Plugins, this.GroupOneAddBefore,
                        this.GroupOne, this.GroupTwo, this.GroupTwoAddBefore,
                        this.GroupThreeAddBefore, this.GroupThree, 
                        this.ToolbarLocation,this.ToolbarAlign, 
                        this.PathLocation, this.DateFormat, this.TimeFormat,
                        this.ExtendedValidElements,
                        this.ExternalLinkListUrl,
                        this.ExternalImageListUrl);
            writer.WriteLine(s);
            //for (int i = 0; i < config.Count; i++)
            //{
            //    writer.WriteLine(config.GetKey(i) + " : \"" + config.Get(i) + "\",");
            //}
            ////writer.WriteLine("theme_advanced_resizing : true,");
            ////writer.WriteLine("theme_advanced_resize_horizontal : false,");
            ////writer.WriteLine("relative_urls : false,");
            ////writer.WriteLine("theme_advanced_path : true,");
            
            ////writer.WriteLine("valid_elements : {0},", tinyMCEConfiguration.ValidElements);
            ////writer.WriteLine("invalid_elements : \"{0}\",", tinyMCEConfiguration.InvalidElements);

            writer.WriteLine("elements : \"" + UniqueID + "\"");

            writer.WriteLine("});");

            writer.WriteLine("</script>\n");
            writer.WriteLine("<!-- /tinyMCE -->\n");
            writer.WriteLine("<div  id=\"" + UniqueID + "\" name=\"" + UniqueID + "\">");
            writer.Write(Text);
            writer.WriteLine("</div>");

            //if (Cols > 0)
            //    writer.Write("<textarea class=\"tinymce" + UniqueID + "\" id=\"" + UniqueID + "\" name=\"" + UniqueID + "\" cols=\"" + Cols + "\" rows=\"" +
            //                 Rows + "\" style=\"width: 100%\">\n");
            //else
            //    writer.Write("<textarea  id=\"" + UniqueID + "\" name=\"" + UniqueID + "\">\n");
            //writer.Write(Text);
            //writer.WriteLine("</textarea>");
        }

        private string formatMedia(string html)
        {
            return null;
        }


        private string getLocalMediaPath()
        {
            return null;            
        }


     

        private static readonly object TextChangedEvent = new object();

        /// <summary>
        /// Raises an event when the text in the editor changes.
        /// </summary>
        public event EventHandler TextChanged
        {
            add { Events.AddHandler(TextChangedEvent, value); }
            remove { Events.RemoveHandler(TextChangedEvent, value); }
        }

        /// <summary>
        /// Event for text change.
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnTextChanged(EventArgs e)
        {
            if (Events != null)
            {
                EventHandler oEventHandler = (EventHandler) Events[TextChangedEvent];
                if (oEventHandler != null)
                {
                    oEventHandler(this, e);
                }
            }
        }

        /// <summary>
        /// Called when a postback occurs on the page the control is placed at
        /// </summary>
        /// <param name="postDataKey">The key of the editor data</param>
        /// <param name="postCollection">All the posted data</param>
        /// <returns></returns>
        bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            string newText = postCollection[postDataKey];

            if (newText != Text)
            {
                Text = newText;
                return true;
            }

            return false;
        }

        /// <summary>
        /// Raises an event when postback occurs
        /// </summary>
        void IPostBackDataHandler.RaisePostDataChangedEvent()
        {
            OnTextChanged(EventArgs.Empty);
        }
    }

    public enum TinyMceButtons
    {
        code,
        bold,
        italic,
        underline,
        strikethrough,
        justifyleft,
        justifycenter,
        justifyright,
        justifyfull,
        bullist,
        numlist,
        outdent,
        indent,
        cut,
        copy,
        pasteword,
        undo,
        redo,
        link,
        unlink,
        image,
        table,
        hr,
        removeformat,
        sub,
        sup,
        charmap,
        anchor,
        umbracomacro
    }
}